package web.init;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import DB.DB_connection_pool;
import bean.Questionnaire;

public class Questionnaire_init extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	public void init(ServletConfig config) throws ServletException {
		try {
		  	String select_sql = "select * from system_question_paper where questionnaire_release = 1";
			
    	Connection conn = DB_connection_pool.data_pool.getConnection();
		PreparedStatement ps_select = conn.prepareStatement(select_sql);
		ResultSet rs = ps_select.executeQuery();
		
		List<Questionnaire> questionnaires = new ArrayList<Questionnaire>();
		int questionnaire_count = 0;
		while(rs.next()){
			Questionnaire questionnaire = new Questionnaire();
			
			questionnaire.setQuestionnaire_id(rs.getString("questionnaire_id"));
			questionnaire.setQuestionnaire_date(rs.getTimestamp("questionnaire_date"));
			questionnaire.setQuestionnaire_theme(rs.getString("questionnaire_theme"));
			questionnaire.setQuestionnaire_content(new JSONArray(rs.getString("questionnaire_content")));
			questionnaire.setQuestionnaire_release(rs.getInt("questionnaire_release"));
			
			questionnaires.add(questionnaire);
			questionnaire_count++;
		}

		config.getServletContext().setAttribute("questionnaires", questionnaires);
		config.getServletContext().setAttribute("questionnaire_count", questionnaire_count);
    	
		rs.close();
		ps_select.close();
		conn.close();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
